package swing.chapter03;

import swing.util.SwingConsle;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * 组合框 （下拉列表）
 */
public class ComboBox2 extends JFrame {
    private JComboBoxItem<Integer, String> [] language = new JComboBoxItem[]{
            new JComboBoxItem<>(1, "JAVA"),
            new JComboBoxItem<>(2, "Python"),
            new JComboBoxItem<>(3, "GO"),
            new JComboBoxItem<>(4, "PHP"),
            new JComboBoxItem<>(5, "JS"),
            new JComboBoxItem<>(6, "C++"),
    };
    private JTextField t = new JTextField(15);
    private JComboBox c = new JComboBox();
    private JButton b = new JButton("Add Items");
    private int count = 0;

    public ComboBox2(){
        for(int i=0;i<4;i++){
            c.addItem(language[count++]);
        }

        t.setEditable(false);
        b.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if(count < language.length){
                    c.addItem(language[count++]);
                }
            }
        });

        c.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JComboBoxItem selectItem = (JComboBoxItem) ((JComboBox)e.getSource()).getSelectedItem();
                t.setText("Index: " + c.getSelectedIndex() + " val: " + selectItem.getVal());
            }
        });

        setLayout(new FlowLayout());
        add(t);
        add(c);
        add(b);
    }

    public static void main(String[] args) {
        SwingConsle.run(new ComboBox2(), 200, 175);
    }
}

class JComboBoxItem<V, L>{
    V val;
    L label;

    public JComboBoxItem(V val, L label){
        this.val = val;
        this.label = label;
    }

    public V getVal(){
        return val;
    }

    @Override
    public String toString() {
        return "[" + val + "] " + label;
    }
}
